package filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录验证的过滤器
 */
@WebFilter("/*")
public class LoginFilter implements Filter {

    public void init(FilterConfig config) throws ServletException {
        System.out.println("LoginFilter被初始化");
    }
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //0.强制转换
        HttpServletRequest request=(HttpServletRequest)req;
        HttpServletResponse response=(HttpServletResponse)resp;
        //1.获取资源请求路径
        String uri = request.getRequestURI();
        System.out.println(uri);
        //2.判断是否包含登录相关的资源路径,排除css/js/图片等资源
        ////对资源名进行解析，如果资源名中包含登录用户相关信息，则执行doFilter方法，激活servlet的service方法
        if(uri.contains("/login.jsp")||uri.contains("/login")|| uri.contains("/css/")||uri.contains("/js/")|| uri.contains("/fonts/")){
            //包含，用户就是想登录，放行
            chain.doFilter(req,resp);
        }else{
            //不包含，需要验证用户是否登录
            //3.从session中获取user
            Object user = request.getSession().getAttribute("u1");
            if(user!=null){
                //已登录，放行
                chain.doFilter(req,resp);
            }else{
                //没有登录，跳转到登录页面
                request.setAttribute("login_msg","您尚未登录，请登录");
                request.getRequestDispatcher("/login.jsp").forward(request,response);
            }
        }
    }



    public void destroy() {
        System.out.println("LoginFilter被销毁");
    }
}
